package com.maybach.web.framework.util;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.maybach.common.model.CommonEnumDO;
import com.maybach.common.query.CommonEnumQuery;
import com.maybach.core.manager.CommonEnumManager;
import com.maybach.util.AssertUtil;
import com.maybach.util.SpringContextUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by houenxun on 16/1/14.
 */
public class CommonEnumTool {
    Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    protected CommonEnumManager commonEnumManager;

    /**
     * 获取分组内的数据列表
     * @param groupCode
     * @return
     */
    public List<CommonEnumDO> getByGroup(String groupCode) {
        AssertUtil.notBlank(groupCode, "groupCode");
        CommonEnumQuery query = new CommonEnumQuery();
        CommonEnumQuery.Criteria criteria  = query.or();
        criteria.andGroupCodeEqualTo(groupCode);
        criteria.andStatusEqualTo(0);
        query.setOrderByClause(" sort_order ");
        return this.getCommonEnumManager().selectByQuery(query);
    }

    /**
     * 根据code和名称获取分组名称
     * @param groupCode
     * @param code
     * @return
     */
    public String getName(String groupCode, Object code) {
        if(StringUtils.isBlank(groupCode)|| null == code){
            return null;
        }
        CommonEnumQuery query = new CommonEnumQuery();
        CommonEnumQuery.Criteria criteria = query.or();
        criteria.andGroupCodeEqualTo(groupCode);
        criteria.andCodeEqualTo(String.valueOf(code));
        List<CommonEnumDO> list = this.getCommonEnumManager().selectByQuery(query);

        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else if (list.size() == 1) {
            return list.get(0).getName();
        } else {
            for (CommonEnumDO enumDO : list) {
                if (enumDO.getStatus() == 0) {
                    return enumDO.getName();
                }
            }
            return list.get(0).getName();
        }
    }

    protected CommonEnumManager getCommonEnumManager(){
        if(null == commonEnumManager) {
            synchronized (this) {
                if (null == commonEnumManager) {
                    commonEnumManager = SpringContextUtil.getBean(CommonEnumManager.class);
                }

            }
        }
        return commonEnumManager;
    }

}
